package orgs.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import orgs.example.mapper.CustomerMapper;
import orgs.example.pojo.Cancellation;
import orgs.example.pojo.MeetingRoom;
import orgs.example.pojo.Reservation;
import orgs.example.pojo.Result;
import orgs.example.service.CustomerService;
import orgs.example.service.StaffService;
import orgs.example.service.UserService;
import orgs.example.service.impl.CustomerServiceImpl;
import orgs.example.utils.EntityToMap;

import javax.swing.text.html.parser.Entity;
import java.util.*;

@RestController
@RequestMapping("/staff")
@Validated
public class StaffController {

    @Autowired
    private StaffService staffService;

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerService customerService;

    @PostMapping("searchunsubscribeorder")
    public Result<Object> searchunsubscribeorder(@RequestBody Map<String,Object> params) throws Exception{

        String unsunscribeTime = (String) params.get("unsubscribeTime");

        List<Cancellation> lists = staffService.searchAllCancellation();


        if(!unsunscribeTime.equals("")){

            Integer Time = Integer.parseInt(unsunscribeTime.split(" ")[1]);

            Iterator<Cancellation> iterator = lists.iterator();

            while(iterator.hasNext()) {

                Cancellation c = iterator.next();

                Date cancelorderTime = c.getCancelOrdertime();
                Integer reserveId = c.getReserveId();
                Reservation reservation = staffService.searchReserveByreserveId(reserveId);
                Date reserveStart = reservation.getReserveStart();
                Integer ceil = (int) Math.ceil((double) (reserveStart.getTime() - cancelorderTime.getTime()) / (1000 * 60 * 60));

                if (Time != 72 && (ceil < Time || ceil > Time + 24)) {
                    iterator.remove();
                } else if (Time == 72 && (ceil < Time)) {
                    iterator.remove();
                }
            }

        }
        List<Map<String,Object>> result = new ArrayList<>();

        for(Cancellation c : lists){

            Integer reserveId = c.getReserveId();
            Reservation reservation = staffService.searchReserveByreserveId(reserveId);

            Integer roomId = reservation.getRoomId();
            Integer userId = reservation.getUserId();

            String roomName = staffService.searchRoomByRoomId(roomId).getRoomName();
            String userAccount = userService.findByUserId(userId).getUserAccount();

            Map<String, Object> objectMap = EntityToMap.convertIgnoreNull(c);

            objectMap.put("roomId",roomId);
            objectMap.put("userId",userId);
            objectMap.put("roomName",roomName);
            objectMap.put("userAccount",userAccount);

            result.add(objectMap);
        }

        return Result.success("查询成功",result);

    }

    @PostMapping("/unsubscribereview")
    public Result unsubscribereview(@RequestBody Cancellation cancellation){

        Integer cancelId = cancellation.getCancelId();
        String cancelStatus = cancellation.getCancelStatus();

        Cancellation cancellation1 = staffService.searchCancellationByCancellationId(cancelId);

        Reservation reservation = staffService.searchReserveByreserveId(cancellation1.getReserveId());

        staffService.changCancellationStatus(cancelId,cancelStatus);

        staffService.changCancellationProcessBycancelId(cancelId);

        if(cancelStatus.equals("已退款")){
            String reserveStatus = "已取消";
            staffService.changeReservationStatus(cancellation1.getReserveId(),reserveStatus);
        }

        MeetingRoom room = staffService.searchRoomByRoomId(reservation.getRoomId());

//        Date reserveStart = reservation.getReserveStart();

        List<Reservation> reservations = staffService.searchAllReservation();

        for(Reservation r:reservations){
            if(r.getRoomId()==room.getRoomId() && r.getReserveStatus().equals("已支付")){
                System.out.println(room.getRoomId() + " 已改为预定");
                staffService.changeRoomStatus(room.getRoomId(),"预定");
                break;
            }else{
                System.out.println(room.getRoomId() + " 已改为空闲");
                staffService.changeRoomStatus(room.getRoomId(),"空闲");
            }
        }

        return Result.success("退订成功");


    }

    @PostMapping("/searchstatus")
    public Result<Object> searchstatus(@RequestBody Map<String,Object> params){
        String roomStatus = (String) params.get("roomStatus");

        Date now = new Date();

        List<Reservation> lists = staffService.searchAllReservation();

        Iterator<Reservation> iterator = lists.iterator();
        while(iterator.hasNext()){
            Reservation r = iterator.next();

            Date reserveStart = r.getReserveStart();
            Date reserveEnd = r.getReserveEnd();

            Integer roomid = r.getRoomId();

            if(now.before(reserveEnd) && now.after(reserveStart) && r.getReserveStatus().equals("已支付")){
                staffService.changeRoomStatus(roomid,"使用");
            }
        }

        List<MeetingRoom> rooms = staffService.searchAllRoom();

        if(roomStatus.equals("")) {
            rooms.sort(Comparator.comparing(
                    r -> getStatusPriority(r.getRoomStatus())
            ));
        }else{
            Iterator<MeetingRoom> iterator1 = rooms.iterator();
            while(iterator1.hasNext()){
                MeetingRoom next = iterator1.next();
                if(!next.getRoomStatus().equals(roomStatus)){
                    iterator1.remove();
                }
            }
        }
        return Result.success("查询成功",rooms);
    }


    @PostMapping("/changeroomstatus")
    public Result changeroomstatus(@RequestBody MeetingRoom room){

        List<Reservation> reservations = customerService.searchAllReservationByRoomId(room.getRoomId());

        for (Reservation r:reservations){
            Date now = new Date();
            if(now.after(r.getReserveStart()) && now.before(r.getReserveEnd())){
                staffService.changeReservationStatus(r.getReserveId(),"已完成");
            }
        }
        staffService.changeRoomStatus(room.getRoomId(),room.getRoomStatus());

        return Result.success("更改成功");
    }

    private  int getStatusPriority(String status) {
        switch (status) {
            case "维护":
                return 1;
            case "使用":
                return 2;
            case "空闲":
                return 3;
            case "预订":
                return 4;
            default:
                return 99; // 其他状态赋予一个较大的优先级数值，排在后面
        }
    }

}
